package org.jactao.registry;

import org.jactao.common.LConstants;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * Created by fanzetao on 2018/4/8.
 * 默认服务注册约定格式：key = className&version, value = ip&port&weight&...
 */
public class LRedisRegistry implements LRegistry {

    private String host;
    private int port;
    private String password;
    private Jedis jedis;

    public LRedisRegistry(String host, int port, String password) {
        this.host = host;
        this.port = port;
        this.password = password;
    }

    public LRedisRegistry(String host, int port) {
        this.host = host;
        this.port = port;
    }

    @Override
    public void init() {
        jedis = new Jedis(host, port, 5000);
        if(password != null && password != "")
            jedis.auth(password);
    }

    @Override
    public boolean running() {
        return jedis != null;
    }

    @Override
    public void destroy() {
        jedis.close();
    }

    @Override
    public void register(LRegistryInfo lRegistryInfo) {
        jedis.sadd(lRegistryInfo.defaultKey(), lRegistryInfo.defaultValue());
    }

    @Override
    public void register(List<LRegistryInfo> registryInfoList) {
        if(registryInfoList != null && ! registryInfoList.isEmpty()) {
            Pipeline pl = jedis.pipelined();
            for(LRegistryInfo lRegistryInfo : registryInfoList) {
                pl.sadd(lRegistryInfo.defaultKey(), lRegistryInfo.defaultValue());
            }
            pl.sync();
        }
    }

    @Override
    public List<LRegistryInfo> get(String serviceName, String version) {
         Set<String> members = jedis.smembers(serviceName + LConstants.defaultSeparate + version);
         if(members != null && ! members.isEmpty()) {
             List<LRegistryInfo> registryInfoList = new ArrayList<>();
             Iterator<String> it = members.iterator();
             while (it.hasNext()) {
                 String value = it.next();
                 LRegistryInfo registryInfo = new LRegistryInfo();
                 registryInfo.setServiceName(serviceName);
                 registryInfo.setVersion(version);

                 String[] valueArr = value.split(LConstants.defaultSeparate);
                 registryInfo.setAddress(new InetSocketAddress(valueArr[0], Integer.valueOf(valueArr[1])));
                 registryInfo.setWeight(Integer.valueOf(valueArr[2]));
                 registryInfoList.add(registryInfo);
             }
             return registryInfoList;
         }

         return null;
    }
}
